//
//  HMComposeTextView.swift
//  HMSlender
//
//  Created by 赵少朋赵少朋 on 2017/2/10.
//  Copyright © 2017年 ITheima. All rights reserved.
//

import UIKit

class HMComposeTextView: UITextView {

    //定义闭包 当有内容的时候让发送按钮可以点击
    var closure:((Bool)->())?
    
    // 设置属性供外界设置占位文字
    var placeholder: String? {
    
        didSet {
            
            placeholderLabel.text = placeholder
        }
    }
    
    //监听文本视图文字的font 同时给占位文字设置大小
    override var font: UIFont? {
    
        didSet {
            
            placeholderLabel.font = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() -> Void {
        
        
        //加载站位文字
        addSubview(placeholderLabel)
        
        //约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: -5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 8))
        
        //通过系统通知监听textView文字改变
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
    }
    
    //懒加载label
    private lazy var placeholderLabel: UILabel = {
    
        let lab = UILabel()
        
        lab.text = "分享新鲜事..."
        lab.textColor = UIColor.darkGray
        
        return lab
    }()
    
    /// 文本视图文字发生改变
    func textChange() -> Void {
        
        //有文字就隐藏站位文字 没有文字就显示占位文字
        if self.hasText {
        
            placeholderLabel.isHidden = true
            //调用闭包 让发送按钮可以点击
            closure?(true)
        } else {
            
            placeholderLabel.isHidden = false
            closure?(false)
        }
        
        
    }
    
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

